//
//  ShopHomeViewController.m
//  CYWFrame
//
//  Created by 于顺燊 on 2018/10/10.
//  Copyright © 2018年 Macx. All rights reserved.
//

#import "ShopHomeViewController.h"
#import "Goods.h"
#import "MallsCollectionViewCell.h"
#import "MallDetailViewController.h"
#import "ShopHomeHeaderView.h"
#import "LiveRoomViewControllerAudience.h"
#import "LiveRoomViewController.h"
#import "Live.h"
#import "ShopLocationInfo.h"


@interface ShopHomeViewController () <UICollectionViewDelegate, UICollectionViewDataSource,UISearchBarDelegate, LiveRoomVCADelegate>

@property (nonatomic, assign) NSInteger page; // 网络请求页数
@property (nonatomic, strong) NSMutableArray *infoArr;

@property (strong, nonatomic) ShopLocationInfo *shopInfo;
@property (strong, nonatomic) UIView *headBgView;
@property (strong, nonatomic) UICollectionView *collectionView;
@property (strong, nonatomic) UIButton *returnBtn;
@property (assign, nonatomic) CGFloat collectionW;
@property (assign, nonatomic) CGFloat collectionH;
@property (nonatomic, assign) NSInteger isPush;
@property (nonatomic, retain) LiveRoomViewControllerAudience *liveRoomVCAudience;

//AgoraLive
@property (assign, nonatomic) AgoraVideoProfile videoProfile;
@property (assign, nonatomic) AgoraClientRole clientRole;

@property (strong, nonatomic) ShopHomeHeaderView *headerView;

@property (assign, nonatomic) BOOL hasEnterplayVC;

@property (strong, nonatomic) NSString *keyword;

@end

@implementation ShopHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
	self.page = 1;
	[self createUI];
	[self GETMallsGoods];
	self.videoProfile = AgoraVideoProfileLandscape480P;
	self.clientRole = AgoraClientRoleAudience;
}

- (void)viewWillAppear:(BOOL)animated {
	[self.navigationController setNavigationBarHidden:YES animated:animated];
	
}
- (void)viewWillDisappear:(BOOL)animated {
	[self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)createUI {
	self.view.backgroundColor = UISeparatedColorRGB;
	
	_headBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 64)];
	[self.view addSubview:_headBgView];
	_headBgView.backgroundColor = UIMainColorRGB;
	// 返回btn
	_returnBtn = [UIButton buttonWithType:UIButtonTypeCustom];
	[_headBgView addSubview:_returnBtn];
	[_returnBtn setImage:IMAGE(@"return") forState:UIControlStateNormal];
	[_returnBtn addTarget:self action:@selector(returnClick) forControlEvents:UIControlEventTouchUpInside];
	_returnBtn.frame = CGRectMake(0, 20, 44, 44);
	
	UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(44, 0, SCREEN_WIDTH-60, 30)];
	searchBar.centerY = _returnBtn.centerY;
	searchBar.placeholder = @"请输入搜索内容…";
	searchBar.backgroundImage = IMAGE(@"clearImage");
	searchBar.layer.cornerRadius = searchBar.height/2;
	searchBar.layer.masksToBounds = YES;
	searchBar.delegate = self;
	UIView *searchTextField = searchTextField = [searchBar valueForKey:@"_searchField"];
	searchTextField.backgroundColor = [UIColor colorWithRed:234/255.0 green:235/255.0 blue:237/255.0 alpha:1];
	[_headBgView addSubview:searchBar];
	[[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setTintColor:kWhiteColor];
	[[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setTitle:@"取消"];
	
	// 集合视图 collectionView所有布局的父类
	// 系统提供自带的布局类
	UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
	// 默认为纵向滑动
	flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
	flowLayout.minimumInteritemSpacing = 5;
	flowLayout.minimumLineSpacing = 5;
	
	// 创建collectionView
	_collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, _headBgView.y+_headBgView.height, SCREEN_WIDTH, SCREEN_HEIGHT-64) collectionViewLayout:flowLayout];
	[self.view addSubview:_collectionView];
	_collectionView.backgroundColor = UISeparatedColorRGB;
	_collectionView.delegate = self;
	_collectionView.dataSource = self;
	
	[_collectionView registerNib:[UINib nibWithNibName:@"MallsCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"item"];
	
	[_collectionView registerClass:[ShopHomeHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
	
	
	//[_collectionView registerNib:[UINib nibWithNibName:@"ShopHomeHeaderView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
	
	
	CGSize size1 = [LZCTools textSizeWithText:@"x" font:kUHSystemFontWithSize(12)];
	
	_collectionW = (SCREEN_WIDTH-30)/2;
	_collectionH = _collectionW+20+size1.height*3;
	
}

#pragma mark ==========UICollectionView==========

//创建头视图
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView
		   viewForSupplementaryElementOfKind:(NSString *)kind
								 atIndexPath:(NSIndexPath *)indexPath {
	NSString *reuseIdentifier;
	if ([kind isEqualToString:UICollectionElementKindSectionHeader])
	{ // header
		reuseIdentifier = @"header";
		ShopHomeHeaderView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind
																				  withReuseIdentifier:reuseIdentifier
																						 forIndexPath:indexPath];
		if (![NSString isEmpty:self.shopInfo.addr]) {
			headerView.address.text = self.shopInfo.addr;
		}
		else {
			headerView.address.text = @"尚未填写";
		}
		headerView.shopName.text = self.shopInfo.shop_name;
		[headerView.shopImg sd_setImageWithURL:[NSURL URLWithString:self.shopInfo.photo]];
		headerView.phone.text = self.shopInfo.tel;
		headerView.openTime.text = self.shopInfo.shop_hours;
		
		int thinkEnv = [LZCTools thinkEnv];
		if(self.shopInfo.is_live == 1 && thinkEnv != 0){
			headerView.joinLive.hidden = NO;
			[headerView.joinLive addActionWithblock:^{
				//现在业务逻辑是可以从正在直播的直播间点击主播头像跳到他的商店主页，所以如果是从直播间来的，那就pop回去，不是的话才走进入直播间流程
				if (self.isFromLive) {
					[self.navigationController popViewControllerAnimated:YES];
				}
				else {
					[self PUTLive:self.shopInfo.user_id];
				}
				
			}];
		}
		else {
			headerView.joinLive.hidden = YES;
		}
		
		self.headerView = headerView;
		return headerView;
	}
	else {
		return nil;
	}
	

}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
	
	MallsCollectionViewCell *item = [collectionView dequeueReusableCellWithReuseIdentifier:@"item" forIndexPath:indexPath];

	item.model = self.infoArr[indexPath.row];
	
	return item;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
	return self.infoArr.count;
}
//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
	
	return CGSizeMake(_collectionW, _collectionH);
}
//定义每个UICollectionView 的 margin
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
	return UIEdgeInsetsMake(10, 10, 10, 10);
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
	
	NSLog(@"点击collectionView.item = %ld", indexPath.row);
	
	Goods *model = self.infoArr[indexPath.row];
	
	MallDetailViewController *detailVC = [[MallDetailViewController alloc] init];
	detailVC.goodId = model.goods_id;
	detailVC.isBuytogetherMode = model.is_ecbuy;
	[self.navigationController pushViewController:detailVC animated:YES];
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
	
	return CGSizeMake(SCREEN_WIDTH, 198);
}

#pragma mark ==========更新数据==========
- (void)refreshData {
	__weak typeof (self) weakSelf = self;
	
	_collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
		NSLog(@"上拉加载");
		weakSelf.page++;
		[weakSelf GETMallsGoods];
	}];
	
}

#pragma mark ===========响应方法==========
- (void)GETMallsGoods {
	if (!self.keyword) {
		self.keyword = @"";
	}
	NSDictionary *param;
	if (self.isFromLive) {
		param = @{
				  @"user_id":self.userId,
				  @"keyword":self.keyword
				  };
	}
	else {
		param = @{
					@"shop_id":self.shopId,
					@"keyword":self.keyword
					};
	}
	[[NetworkTool sharedTool] requestWithName:@"获取该商店所有商品" URLString:APIShopHome parameters:param method:@"POST" callBack:^(id responseObject) {
		
		NSArray *arr = responseObject[@"data"][@"goods"];
		NSDictionary *dict = responseObject[@"data"][@"shop"];
		[self.shopInfo setValuesForKeysWithDictionary:dict];
		if (self.page == 1) {
			[self.infoArr removeAllObjects];
		}
		
		if (arr.count == 0) {
			self.page--;
			if (self.page == 0) {
				self.page = 1;
			}
		}
		
		for (NSDictionary *dic in arr) {
			Goods *model = [[Goods alloc] init];
			[model setValuesForKeysWithDictionary:dic];
			[self.infoArr addObject:model];
		}
		
		dispatch_async(dispatch_get_main_queue(), ^{
			[MBProgressHUD hideHUDForView:self.view animated:YES];
			[_collectionView.mj_footer endRefreshing];
			[_collectionView reloadData];
		});
		
	}];
}

//商品搜索
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
	self.keyword = searchBar.text;
	self.page = 1;
	[searchBar resignFirstResponder];
	[self GETMallsGoods];
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
	return YES;
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
	NSLog(@"开始输入搜索内容");
	
	// 取消字体颜色？
	searchBar.showsCancelButton = YES;
	[searchBar setShowsCancelButton:YES animated:YES];
	UITextField *searchBarTextField = nil;
	NSArray *views = ([[[UIDevice currentDevice] systemVersion] floatValue] < 7.0) ? searchBar.subviews : [[searchBar.subviews objectAtIndex:0] subviews];
	for (UIView *subview in views)
	{
		if ([subview isKindOfClass:[UITextField class]])
		{
			searchBarTextField = (UITextField *)subview;
			break;
			
		}
	}
	searchBarTextField.enablesReturnKeyAutomatically = NO;
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
	NSLog(@"输入搜索完毕");
	
	[searchBar setShowsCancelButton:NO animated:YES];
	[searchBar resignFirstResponder];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
	NSLog(@"取消搜索");
	
	[searchBar setShowsCancelButton:NO animated:YES];
	[searchBar resignFirstResponder];
}

- (void)returnClick {
	[self.navigationController popViewControllerAnimated:YES];
}

/**
 进入直播间
 */
- (void)PUTLive:(NSString *)userId {
	
	if (GetUserDefaule(USERINFO) == NULL) {
		[self presentViewController:[LZCTools alertMessage:@"请先登录"]animated:YES completion:nil];
		return;
	}
	
	// PUT /users/{uid}/lives 进入直播间 只有主播进入都会有推流地址 uid * 主播ID
	NSString *url = [APIUser stringByAppendingFormat:@"/%@/lives", userId];
	
	[[NetworkTool sharedTool] requestWithName:@"进入直播间" URLString:url parameters:nil method:@"PUT" callBack:^(id responseObject) {
		
		if ([[GetUserDefaule(USERINFO) valueForKey:@"user_id"] isEqualToString:userId]) {
			NSLog(@"这个直播是自己的直播，走创建直播流程");
			self.clientRole = AgoraClientRoleBroadcaster;
			Live *model = [[Live alloc] init];
			[model setValuesForKeysWithDictionary:[responseObject valueForKey:@"data"]];
			
			
			TCLiveInfo *info = [[TCLiveInfo alloc] init];
			info.userinfo = [[TCLiveUserInfo alloc] init];
			
			info.userid = [model.anchor valueForKey:@"user_id"];
			info.groupid = model.chatroom_id;
			info.likecount = [model.like_num intValue];
			info.title = model.title;
			//        info.playurl = model.pull_url[0]; // rtmp 默认第一个
			info.playurl = [model.pull_multi_urls valueForKey:@"rtmp_lsd"]; //拉流地址，键名后缀代表清晰度，无则代表原画 lud-超清 lhd-高清 lsd-标清 lld-流畅，如rtmp_lud:’rtmp://xxx’,代表超清的rtmp 默认标清，切换超清
			info.biaoUrl = [model.pull_multi_urls valueForKey:@"rtmp_lsd"];
			info.gaoUrl = [model.pull_multi_urls valueForKey:@"rtmp_lud"];
			info.timestamp = [model.start_time intValue];
			info.userinfo.nickname = [model.anchor valueForKey:@"nickname"];
			info.userinfo.headpic = [model.anchor valueForKey:@"face"];
			info.userinfo.frontcover = [model.anchor valueForKey:@"face"];
			info.isLike = [NSString stringWithFormat:@"%@", [model.anchor valueForKey:@"is_like"]];
			//        info.money = [model.anchor valueForKey:@"money"];
			info.money = [NSString stringWithFormat:@"%ld", model.stars_count];
			info.isPraise = [NSString stringWithFormat:@"%ld", model.is_like];
			
			info.viewercount = (int)model.viewer_num;
			info.roomid = [NSString stringWithFormat:@"%ld", (long)model.liveId];
			
			//        info.isVip = [self.liveData[@"anchor"] valueForKey:@"is_enterprise"];
			
			info.isVip = [NSString stringWithFormat:@"%@", [model.anchor valueForKey:@"role"]];
			info.myuserid = [model.anchor valueForKey:@"user_id"];
			
			
			// 保存直播信息，后面用到
			NSDictionary *live = @{@"hostId":info.userid, @"groupId":info.groupid};
			SetUserDefaule(live, CURRLIVE);
			
			NSDictionary *userinfo = GetUserDefaule(USERINFO);
			
			NSDictionary *infoDict = @{@"imId":[userinfo valueForKey:@"user_id"],
									   @"uid":[userinfo valueForKey:@"user_id"],
									   @"nickname":[userinfo valueForKey:@"nickname"],
									   @"headpic":[userinfo valueForKey:@"face"],
									   @"level":[NSString stringWithFormat:@"%@", [userinfo valueForKey:@"level"]]};
			
			
			NSError *parseError = nil;
			NSData *jsonData = [NSJSONSerialization dataWithJSONObject:infoDict options:NSJSONWritingPrettyPrinted error:&parseError];
			NSString *infoStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
			
			info.senderInfo = infoStr;
			UIStoryboard *agoraSB = [UIStoryboard storyboardWithName:@"AgoraLive" bundle:nil];
			LiveRoomViewController *agoraLiveRoomVC = (LiveRoomViewController *)[agoraSB instantiateViewControllerWithIdentifier:@"AgoraLiveRoomVC"];
			agoraLiveRoomVC.channelId = info.groupid;
			agoraLiveRoomVC.liveInfo = info;
			agoraLiveRoomVC.videoProfile = self.videoProfile;
			agoraLiveRoomVC.clientRole = self.clientRole;
			agoraLiveRoomVC.isEnterSelf = 1;
			UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:agoraLiveRoomVC];
			
			// 设置导航背景风格颜色
			nav.navigationBar.barTintColor = UIMainColorRGB;
			[nav.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:kWhiteColor}];
			
			[self presentViewController:nav animated:YES completion:nil];
			
		}
		else {
			Live *model = [[Live alloc] init];
			[model setValuesForKeysWithDictionary:[responseObject valueForKey:@"data"]];
			
			
			TCLiveInfo *info = [[TCLiveInfo alloc] init];
			info.userinfo = [[TCLiveUserInfo alloc] init];
			
			info.userid = [model.anchor valueForKey:@"user_id"];
			info.groupid = model.chatroom_id;
			info.likecount = [model.like_num intValue];
			info.title = model.title;
			//        info.playurl = model.pull_url[0]; // rtmp 默认第一个
			info.playurl = [model.pull_multi_urls valueForKey:@"rtmp_lsd"]; //拉流地址，键名后缀代表清晰度，无则代表原画 lud-超清 lhd-高清 lsd-标清 lld-流畅，如rtmp_lud:’rtmp://xxx’,代表超清的rtmp 默认标清，切换超清
			info.biaoUrl = [model.pull_multi_urls valueForKey:@"rtmp_lsd"];
			info.gaoUrl = [model.pull_multi_urls valueForKey:@"rtmp_lud"];
			info.timestamp = [model.start_time intValue];
			info.userinfo.nickname = [model.anchor valueForKey:@"nickname"];
			info.userinfo.headpic = [model.anchor valueForKey:@"face"];
			info.userinfo.frontcover = [model.anchor valueForKey:@"face"];
			info.isLike = [NSString stringWithFormat:@"%@", [model.anchor valueForKey:@"is_like"]];
			//        info.money = [model.anchor valueForKey:@"money"];
			info.money = [NSString stringWithFormat:@"%ld", model.stars_count];
			info.isPraise = [NSString stringWithFormat:@"%ld", model.is_like];
			
			info.viewercount = (int)model.viewer_num;
			info.roomid = [NSString stringWithFormat:@"%ld", (long)model.liveId];
			
			//        info.isVip = [self.liveData[@"anchor"] valueForKey:@"is_enterprise"];
			
			info.isVip = [NSString stringWithFormat:@"%@", [model.anchor valueForKey:@"role"]];
			info.myuserid = [model.anchor valueForKey:@"user_id"];
			
			
			// 保存直播信息，后面用到
			NSDictionary *live = @{@"hostId":info.userid, @"groupId":info.groupid};
			SetUserDefaule(live, CURRLIVE);
			
			NSDictionary *userinfo = GetUserDefaule(USERINFO);
			
			NSDictionary *infoDict = @{@"imId":[userinfo valueForKey:@"user_id"],
									   @"uid":[userinfo valueForKey:@"user_id"],
									   @"nickname":[userinfo valueForKey:@"nickname"],
									   @"headpic":[userinfo valueForKey:@"face"],
									   @"level":[NSString stringWithFormat:@"%@", [userinfo valueForKey:@"level"]]};
			
			
			NSError *parseError = nil;
			NSData *jsonData = [NSJSONSerialization dataWithJSONObject:infoDict options:NSJSONWritingPrettyPrinted error:&parseError];
			NSString *infoStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
			
			info.senderInfo = infoStr;
			
			// MARK: 打开播放界面
			/*
			 if (_playVC == nil) {
			 _playVC = [[TCPlayViewController_LinkMic alloc] initWithPlayInfo:info videoIsReady:^{
			 if (!_hasEnterplayVC) {
			 self.isPush = 1;
			 [self.navigationController pushViewController:_playVC animated:YES];
			 _hasEnterplayVC = YES;
			 }
			 }];
			 }
			 */
			
			if (_liveRoomVCAudience == nil) {
				UIStoryboard *agoraSB = [UIStoryboard storyboardWithName:@"AgoraLive" bundle:nil];
				_liveRoomVCAudience = (LiveRoomViewControllerAudience *)[agoraSB instantiateViewControllerWithIdentifier:@"AgoraLiveRoomVCA"];
				if (!_hasEnterplayVC && _liveRoomVCAudience) {
					self.isPush = 1;
					_liveRoomVCAudience.channelId = info.groupid;
					_liveRoomVCAudience.clientRole = self.clientRole;
					_liveRoomVCAudience.videoProfile = self.videoProfile;
					_liveRoomVCAudience.delegate = self;
					_liveRoomVCAudience.liveInfo = info;
					_hasEnterplayVC = YES;
					[self.navigationController pushViewController:_liveRoomVCAudience animated:YES];
					return;
				}
			}
			
			[self performSelector:@selector(enterPlayVC:) withObject:_liveRoomVCAudience afterDelay:0.5];
		}
	}];
}

-(void)enterPlayVC:(NSObject *)obj{
	if (!_hasEnterplayVC) {
		self.isPush = 1;
		[self.navigationController pushViewController:_liveRoomVCAudience animated:YES];	//这行的VC也改了，到时候要回滚的时候记得改过来
		_hasEnterplayVC = YES;
	}
}

//MARK: - AgoraLive delegates

- (void)liveVCNeedClose:(LiveRoomViewControllerAudience *)liveVC {
	//[self dismissViewControllerAnimated:YES completion:nil];
	[self.navigationController popViewControllerAnimated:YES];
	_hasEnterplayVC = NO;
	_liveRoomVCAudience = nil;
	self.clientRole = AgoraClientRoleAudience;
}

- (NSMutableArray *)infoArr
{
	if (!_infoArr) {
		_infoArr = [[NSMutableArray alloc] init];
	}
	return _infoArr;
}

- (ShopLocationInfo *)shopInfo {
	if (!_shopInfo) {
		_shopInfo = [[ShopLocationInfo alloc] init];
	}
	return _shopInfo;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
